package main

import (
	"fmt"
	uuid "github.com/satori/go.uuid"
	"go.uber.org/zap"
	"mxshop-api/user-web/global"
	"mxshop-api/user-web/initialize"
	"mxshop-api/user-web/utils"
	"mxshop-api/user-web/utils/register/consul"
	"os"
	"os/signal"
	"syscall"
)

/*
*
启动入口
*/
func main() {
	//初始化日志
	initialize.InitLogger()

	//初始化配置
	initialize.InitConfig()
	//initialize.InitConfigLocal()

	//初始化路由文件
	routers := initialize.Routers()

	//4 初始化翻译
	if transError := initialize.InitTrans("zh"); transError != nil {
		panic(transError)
	}

	//初始化src的连接
	//initialize.InitSrvConn()
	initialize.InitSrvConnLb()

	//注册到consul
	register_client := consul.NewRegistryClient(global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port)
	serviceID := fmt.Sprintf("%s", uuid.NewV4())
	//获取当前的ip
	ip, errIp := utils.GetHostIp()
	port := global.ServerConfig.Port
	name := global.ServerConfig.Name
	if errIp != nil {
		zap.S().Infof("user-web获取ip失败:%s", errIp.Error())
		return
	}
	zap.S().Infof("user-web获取当前ip:%s", ip)
	tag := []string{"goods-web"}
	errRegister := register_client.Register(ip, port, name, tag, serviceID)
	if errRegister != nil {
		zap.S().Infof("user-web注册失败:%s", errRegister.Error())
		return
	}
	go func() {
		zap.S().Infof("启动user-web的http服务，端口:%d", port)
		err := routers.Run(fmt.Sprintf(":%d", port))
		if err != nil {
			fmt.Println("user web服务启动失败", err.Error())
		}
	}()
	//接收终止信号
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit //在此阻塞
	if errDeregister := register_client.DeRegister(serviceID); errDeregister != nil {
		zap.S().Infof("user-web服务注销失败:%s", errDeregister.Error())
	} else {
		zap.S().Info("user-web服务注销成功")
	}
}
